let mongoose = require("mongoose")
mongoose.connect("mongodb://127.0.0.1/epi_thesis")
let Schema = mongoose.Schema
const bcrypt = require("bcryptjs");

let userSchema = new Schema({
    username:{
        type:String,
        required:true,
        unique:true
    },
    password:{
        type:String,
        required: true
    }
})

//定义模型
let userModel = mongoose.model("user", userSchema, "user");

//注册
const registerModel =async (userInfo) => {
    const userObj = new userModel(userInfo)
    //调用bcrypt.hashSync()对密码进行加密
    userObj.password = bcrypt.hashSync(userObj.password, 10)

    //查看是否有当前用户
    const findUser = () => {
        return userModel.findOne({'username':userObj.username})
            .then(res => res)
            .catch(err => {
                console.log(err)
                return false
            })
    }

    let data = await findUser()
    if (data !== null){
        return new Error('用户已存在')
    }else {
        return userObj.save()
            .then(res=>{
                return res
            })
            .catch(err=>{
                console.log(err)
                return false
            })
    }
}

//登录
const loginModel = async (userInfo) => {
    const loginObj = new userModel(userInfo)

    //查看是否有当前用户
    const findUser = () => {
        return userModel.findOne({'username':loginObj.username})
            .then(res => res)
            .catch(err => {
                console.log(err)
                return false
            })
    }

    let data = await findUser()
    // console.log(data)
    if (data === null){
        return new Error('用户不存在')
    }else {
        return userModel.findOne({username: loginObj.username})
            .then(res=>{
                return res
            })
            .catch(err=>{
                console.log(err)
                return false
            })
    }
}

module.exports = {
    loginModel,
    registerModel
}
